﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections.Specialized;

namespace Inline.SharePoint.ExtendedVariations.Helpers
{

    class ListHandler
    {

        /// <summary>
        /// Will rebuild a list in the other variations of the hierarchy
        /// </summary>
        /// <param name="variationUrls">URL's of all other variations</param>
        /// <param name="properties">Event properties from the event receiver</param>
        public void RebuildListInAllOtherVariations(StringCollection variationUrls, SPListEventProperties properties)
        {

            for (int i = 0; i < variationUrls.Count; i++)
            {

                using (SPSite site = new SPSite(variationUrls[i]))
                {

                    using (SPWeb web = site.OpenWeb())
                    {

                        SPList targetList = web.Lists.TryGetList(properties.List.RootFolder.Name);

                        if (targetList == null) // Create the list if not already there on the target
                        {

                            Guid listId = web.Lists.Add(properties.ListTitle, properties.List.Description, properties.List.BaseTemplate);

                        }

                    }

                }

            }

        }

        public void UpdateListsInAllOtherVariations(StringCollection variationUrls, SPListEventProperties properties)
        {

            for (int i = 0; i < variationUrls.Count; i++)
            {

                using (SPSite site = new SPSite(variationUrls[i]))
                {

                    using (SPWeb web = site.OpenWeb())
                    {

                        SPList targetList = web.Lists.TryGetList(properties.List.RootFolder.Name);

                        if (targetList == null) // Create the list if not already there on the target
                        {

                            Guid listId = web.Lists.Add(properties.ListTitle, properties.List.Description, properties.List.BaseTemplate);
                            targetList = web.Lists[listId];

                        }

                        UpdateSettings(properties.List, targetList);
                        UpdateContentTypes(properties.List, targetList);

                    }

                }

            }

        }

        public void RemoveListFromAllOtherVariations(StringCollection variationUrls, SPListEventProperties properties)
        {

            for (int i = 0; i < variationUrls.Count; i++)
            {

                using (SPSite site = new SPSite(variationUrls[i]))
                {

                    using (SPWeb web = site.OpenWeb())
                    {

                        SPList targetList = web.Lists.TryGetList(properties.List.RootFolder.Name);

                        if (targetList != null) // Create the list if not already there on the target
                        {

                            targetList.Delete();

                        }

                    }

                }

            }

        }

        /// <summary>
        /// Copies all the settings from the source list to the target list
        /// </summary>
        /// <param name="properties.List">The source list to copy properties from</param>
        /// <param name="targetList">The target list to copy properties to</param>
        public void UpdateSettings(SPList sourceList, SPList targetList)
        {

            // Copy all properties if possible
            targetList.AlertTemplate = sourceList.AlertTemplate;
            targetList.AllowDeletion = sourceList.AllowDeletion;
            targetList.AllowEveryoneViewItems = sourceList.AllowEveryoneViewItems;
            targetList.AllowMultiResponses = sourceList.AllowMultiResponses;
            targetList.AnonymousPermMask64 = sourceList.AnonymousPermMask64;
            targetList.BrowserFileHandling = sourceList.BrowserFileHandling;
            targetList.CalculationOptions = sourceList.CalculationOptions;
            targetList.ContentTypesEnabled = sourceList.ContentTypesEnabled;
            targetList.DefaultContentApprovalWorkflowId = sourceList.DefaultContentApprovalWorkflowId;
            targetList.DefaultDisplayFormUrl = sourceList.DefaultDisplayFormUrl;
            targetList.DefaultEditFormUrl = sourceList.DefaultEditFormUrl;
            targetList.DefaultItemOpen = sourceList.DefaultItemOpen;
            targetList.DefaultItemOpenUseListSetting = sourceList.DefaultItemOpenUseListSetting;
            targetList.DefaultNewFormUrl = sourceList.DefaultNewFormUrl;
            targetList.Direction = sourceList.Direction;
            targetList.DraftVersionVisibility = sourceList.DraftVersionVisibility;
            targetList.EmailAlias = sourceList.EmailAlias;
            targetList.EnableAssignToEmail = sourceList.EnableAssignToEmail;
            targetList.EnableAttachments = sourceList.EnableAttachments;
            targetList.EnableDeployWithDependentList = sourceList.EnableDeployWithDependentList;
            targetList.EnableFolderCreation = sourceList.EnableFolderCreation;
            targetList.EnableMinorVersions = sourceList.EnableMinorVersions;
            targetList.EnableModeration = sourceList.EnableModeration;
            targetList.EnablePeopleSelector = sourceList.EnablePeopleSelector;
            targetList.EnableResourceSelector = sourceList.EnableResourceSelector;
            targetList.EnableSchemaCaching = sourceList.EnableSchemaCaching;
            targetList.EnableSyndication = sourceList.EnableSyndication;
            targetList.EnableThrottling = sourceList.EnableThrottling;
            targetList.EnableVersioning = sourceList.EnableVersioning;

            // And so on ...

            targetList.ParentWeb.AllowUnsafeUpdates = true;
            targetList.Update();
            targetList.ParentWeb.AllowUnsafeUpdates = false;

        }

        /// <summary>
        /// Updates the content types collection of the target list with those of the source list
        /// </summary>
        /// <param name="properties.List">The source list to take the content types from</param>
        /// <param name="targetList">The target list to copy new content types to</param>
        public void UpdateContentTypes(SPList sourceList, SPList targetList)
        {

            SPContentTypeCollection contentTypeCollection = sourceList.ContentTypes;
            for (int j = 0; j < contentTypeCollection.Count; j++)
            {

                if (!ContentTypeCollectionContainsContentType(contentTypeCollection, contentTypeCollection[j]))
                    targetList.ContentTypes.Add(contentTypeCollection[j]);

            }

            targetList.ParentWeb.AllowUnsafeUpdates = true;
            targetList.Update();
            targetList.ParentWeb.AllowUnsafeUpdates = false;

        }

        /// <summary>
        /// Checks if a given content tyoe collection contains a given content type
        /// </summary>
        /// <param name="contentTypeCollection">Content type collection</param>
        /// <param name="contentType">Content type</param>
        /// <returns></returns>
        private bool ContentTypeCollectionContainsContentType(SPContentTypeCollection contentTypeCollection, SPContentType contentType)
        {

            for (int i = 0; i < contentTypeCollection.Count; i++)
            {

                if (contentTypeCollection[i].Name == contentType.Name)
                    return true;

            }

            return false;

        }

    }

}